package cn.jdx.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Override //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //设置用户的角色
        Set<String> roleSet = new HashSet<>();
        roleSet.add("user");
        info.setRoles(roleSet);
        //设置用户的权限
        Set<String> addSet = new HashSet<>();
        addSet.add("user:add");
        info.setStringPermissions(addSet);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        password = MD5Utils.getMD5(password);
        System.out.println("[认证处理]账号=" + username + " 密码=" + password);
        if (username.equals("root")){
            return new SimpleAuthenticationInfo(username,password,getName());
        }else {
            return null;
        }
    }
}
